package com.teach.javafx.controller;

import com.teach.javafx.controller.base.MessageDialog;
import com.teach.javafx.util.CommonMethod;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.MapValueFactory;
import com.teach.javafx.request.HttpRequestUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.FlowPane;
import com.teach.javafx.request.DataRequest;
import com.teach.javafx.request.DataResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CourseController 登录交互控制类 对应 course-panel.fxml
 *  @FXML  属性 对应fxml文件中的
 *  @FXML 方法 对应于fxml文件中的 on***Click的属性
 */
public class CourseController {
    @FXML
    private TableView<Map<String, Object>> dataTableView;
    @FXML
    private TableColumn<Map,String> numColumn;
    @FXML
    private TableColumn<Map,String> nameColumn;
    @FXML
    private TableColumn<Map,String> creditColumn;
    @FXML
    private TableColumn<Map,String> preCourseColumn;
    @FXML
    private TableColumn<Map,FlowPane> operateColumn;
    @FXML
    private TableColumn<Map,String> teacherNameColumn;
    @FXML
    private TableColumn<Map,String> coursePathColumn;
    @FXML
    private TextField numNameTextField;
    @FXML
    public TextField nameField;
    @FXML
    public TextField numField;
    @FXML
    public TextField timeField;
    @FXML
    public TextField teacherField;
    @FXML
    public TextField creditField;
    @FXML
    public TextField preCourseField;

    public Integer courseId = null;

    private List<Map<String,Object>> courseList = new ArrayList<>();  // 学生信息列表数据
    private final ObservableList<Map<String,Object>> observableList= FXCollections.observableArrayList();  // TableView渲染列表
    @FXML
    private void onQuery(){
        DataResponse res;
        DataRequest req =new DataRequest();
        res = HttpRequestUtil.request("/api/course/getCourseList",req); //从后台获取所有学生信息列表集合
        if(res != null && res.getCode()== 0) {
            courseList = (List<Map<String, Object>>) res.getData();
        }
        setTableViewData();
    }

    private void setTableViewData() {
       observableList.clear();
       Map<String,Object> map;
        FlowPane flowPane;
        Button saveButton,deleteButton;
            for (int j = 0; j < courseList.size(); j++) {
                map = courseList.get(j);
                flowPane = new FlowPane();
                flowPane.setHgap(10);
                flowPane.setAlignment(Pos.CENTER);
                flowPane.setPrefWidth(150);
                saveButton = new Button("修改");
                saveButton.setId("save"+j);
                saveButton.setOnAction(e->{
                    saveItem(((Button)e.getSource()).getId());
                });
                deleteButton = new Button("删除");
                deleteButton.setId("delete"+j);
                deleteButton.setOnAction(e->{
                    deleteItem(((Button)e.getSource()).getId());
                });
                flowPane.getChildren().addAll(saveButton,deleteButton);
                map.put("operate",flowPane);
                observableList.addAll(FXCollections.observableArrayList(map));
            }
            dataTableView.setItems(observableList);
    }
    public void saveItem(String name){
        if(name == null)
            return;
        int j = Integer.parseInt(name.substring(4));
        Map<String,Object> data = courseList.get(j);
        if (data == null || data.get("num") == null || data.get("num").toString().isEmpty()) {
            MessageDialog.showDialog("课程编号为空，不能提交");
            return;
        }
        data.remove("operate");
        if ( !data.containsKey("preCourseId") ) {
            data.put("preCourseId", null);
            data.put("perCourse",null);
        }
        // 创建请求对象
        DataRequest req = new DataRequest();
        req.add("courseId", data.get("courseId"));
        req.add("num", data.get("num"));
        req.add("name", data.get("name"));
        req.add("credit", data.get("credit"));
        req.add("coursePath", data.get("coursePath"));
        req.add("preCourseId", data.get("preCourseId"));
        req.add("preCourse", data.get("preCourse"));
        req.add("teacherName", data.get("teacherName"));
        // 发请求
        DataResponse res = HttpRequestUtil.request("/api/course/courseSave", req);

        // 处理响应
        if (res != null && res.getCode() == 0) {
            MessageDialog.showDialog("提交成功！");
            onQuery();
        } else {
            MessageDialog.showDialog(res.getMsg());
            onQuery();
        }
    }
    public void deleteItem(String name){
        if(name == null)
            return;
        int j = Integer.parseInt(name.substring(6,name.length()));
        Map data=courseList.get(j);
        int jet= MessageDialog.choiceDialog("确定要删除吗");
        if(jet != MessageDialog.CHOICE_YES) {
            return;
        }
        Integer courseId= CommonMethod.getInteger(data,"courseId");
        DataRequest req=new DataRequest();
        req.add("courseId",courseId);
        DataResponse res=HttpRequestUtil.request("/api/course/courseDelete",req);
        if(res.getCode()==0){
            MessageDialog.showDialog("删除课程成功！");
            onQuery();
        }else{
            MessageDialog.showDialog(res.getMsg());
        }
    }

    @FXML
    public void initialize() {
        dataTableView.setFixedCellSize(60);

        numColumn.setCellValueFactory(new MapValueFactory<>("num"));
        numColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        numColumn.setOnEditCommit(event -> {
            Map<String,Object> map = event.getRowValue();
            map.put("num", event.getNewValue());
        });
        nameColumn.setCellValueFactory(new MapValueFactory<>("name"));
        nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        nameColumn.setOnEditCommit(event -> {
            Map<String, Object> map = event.getRowValue();
            map.put("name", event.getNewValue());
        });
        creditColumn.setCellValueFactory(new MapValueFactory<>("credit"));
        creditColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        creditColumn.setOnEditCommit(event -> {
            Map<String, Object> map = event.getRowValue();
            map.put("credit", event.getNewValue());
        });
        preCourseColumn.setCellValueFactory(new MapValueFactory<>("preCourse"));
        preCourseColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        preCourseColumn.setOnEditCommit(event -> {
            Map<String, Object> map = event.getRowValue();
            map.put("preCourse", event.getNewValue());
        });
        teacherNameColumn.setCellValueFactory(new MapValueFactory<>("teacherName"));
        teacherNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        teacherNameColumn.setOnEditCommit(event -> {
            Map<String, Object> map = event.getRowValue();
            map.put("teacherName", event.getNewValue());
        });
        coursePathColumn.setCellValueFactory(new MapValueFactory<>("coursePath"));
        coursePathColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        coursePathColumn.setOnEditCommit(event -> {
            Map<String, Object> map = event.getRowValue();
            map.put("coursePath", event.getNewValue());
        });
        operateColumn.setCellValueFactory(new MapValueFactory<>("operate"));
        dataTableView.setEditable(true);
        onQuery();
    }
    @FXML
    protected void onQueryButtonClick() {
        String numName = numNameTextField.getText();
        DataRequest req = new DataRequest();
        req.add("numName", numName);
        DataResponse res = HttpRequestUtil.request("/api/course/getCourseList", req);
        if (res != null && res.getCode() == 0) {
            courseList = (List<Map<String, Object>>) res.getData();
            setTableViewData();
        }
    }

    public void onAddButtonClick() {
        if ( numField.getText().isEmpty() ) {
            MessageDialog.showDialog("课程编号为空，不能提交");
            return;
        }
        DataRequest req = new DataRequest();
        req.add("courseId", courseId);
        req.add("num", numField.getText());
        req.add("name", nameField.getText());
        req.add("credit", creditField.getText());
        req.add("preCourse", preCourseField.getText());
        req.add("teacherName", teacherField.getText());
        req.add("coursePath",timeField.getText());
        DataResponse res = HttpRequestUtil.request("/api/course/newCourse", req);
        if(res.getCode()==0){
            MessageDialog.showDialog("添加课程成功！");
            numNameTextField.clear();
            onQuery();
        }else{
            MessageDialog.showDialog(res.getMsg());
        }
    }
}
